﻿using System.Windows;
using Windows.Foundation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Media;
#if WIN81
using Microsoft.Xaml.Interactivity;
#else
using WinRtBehaviors;
#endif

namespace Win8nl.Behaviors
{
  /// <summary>
  /// This behavior clips display of anything that is displayed using a translation
  /// IN the associated object not to be displayed OUTSIDE that object
  /// </summary>
  public class ClipToBoundsBehavior : Behavior<FrameworkElement>
  {
    protected override void OnAttached()
    {
      base.OnAttached();
      this.AssociatedObject.SizeChanged += AssociatedObjectSizeChanged;
      this.AssociatedObject.Loaded += AssociatedObjectLoaded;
    }

    protected override void OnDetaching()
    {
      this.AssociatedObject.SizeChanged -= AssociatedObjectSizeChanged;
      this.AssociatedObject.Loaded -= AssociatedObjectLoaded;
      base.OnDetaching();
    }

    void AssociatedObjectLoaded(object sender, RoutedEventArgs e)
    {
      SetClip();
    }

    void AssociatedObjectSizeChanged(object sender, SizeChangedEventArgs e)
    {
      SetClip();
    }

    private void SetClip()
    {
      this.AssociatedObject.Clip = new RectangleGeometry
      {
        Rect = new Rect(0, 0,
            this.AssociatedObject.ActualWidth, this.AssociatedObject.ActualHeight)
      };
    }
  }
}
